# -*- coding: utf-8 -*-
import wsgiref.handlers
import urllib2
import urllib
import simplejson
from BeautifulSoup import BeautifulSoup,Tag,NavigableString

from google.appengine.ext import webapp
import xmw

class Result:
    def __init__(self):
        self.body=None
        self.url=None
        
class MainPage(xmw.RequestHandler):

    
    def get(self):
        if not self.request.GET.has_key('q'):
            self.render_template(None, 'search_input')
            return
        q=self.request.GET['q']
        q=q.strip()
        if len(q) == 0:
            self.render_template(None, 'search_input')
            return
        
        q=q+" site:www.tianya.cn"
        q=urllib.quote(q.encode("GB18030"))

        #url = 'http://www.google.cn/search?hl=zh-CN&newwindow=1&q=%s'%q
        url = 'http://baidu.com/s?wd=%s'%q
        #print "xxx"
        #print "url:%s"%url

        #request = urllib2.Request(url, None, {'Referer': 'www.tianya.cn'})
        page = urllib2.urlopen(url)
        #page = urllib2.urlopen(url)
        soup = BeautifulSoup(page, fromEncoding="GB18030")
        #soup = BeautifulSoup(page)
        page.close()

        #print soup.prettify()
        #res=soup.find('li',{'class':'g'})
        #print res
        lst_result=[]
        try:
            for i in range(1,10):
                t=soup.find('table',{"id":str(i)})
                c=t.tr.td
                cc=c.contents
            
                title=cc[0]
                url=title["href"]

                body=cc[2]
                a=body.find('a')
                a.extract()

                tag = Tag(soup,"a")
                #tag.string=NavigableString(u'\u767e\u5ea6\u5feb\u7167\u7167')
                tag['href']=url
                tag['onclick']='t(\"%s\");'%url
                
                tag['align']="right"
                tag.contents.append(NavigableString(("在西门外订阅该贴")))
                body.insert(-1,tag)
                self.response.out.write("<BR>title:%s<BR>"%str(title))
                self.response.out.write("<BR>url:%s<BR>"%str(url))
                self.response.out.write("<BR>body:%s<BR>"%str(body))
                result=Result()
                result.body=t
                #result.body=body
                result.url=url
                #lst_result.append(result)
                lst_result.append(t)
        except:
            lst_result=[]
            lst_result.append("抱歉，找不到相关话题")
        
        template_values = {
                           "lst_result":lst_result
                           }    
        self.render_template(template_values, 'search')
        
    

def main():
  application = webapp.WSGIApplication(
                                       [('/search_baidu', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()